/*
 * Copyright (C) 2015-2019 Alibaba Group Holding Limited
 */

/* #define LOG_NDEBUG 0 */
#include <stdint.h>

#include "amp_defines.h"
#include "board_mgr.h"
#include "be_inl.h"

#define MOD_STR "myjs"

int32_t myjs_handle;

static duk_ret_t native_myjs_open(duk_context *ctx)
{
    int8_t ret = -1;
    item_handle_t myjs_handle;
    myjs_handle.handle     = NULL;

    if (!duk_is_string(ctx, 0)) {
        amp_warn(MOD_STR, "parameter must be string");
        goto out;
    }

	ret = 0;
	myjs_handle.handle = (void *)&myjs_handle;
    amp_debug(MOD_STR, "_____>>>>>> native_myjs_open\n");

out:
    if (0 != ret) {
        duk_push_pointer(ctx, NULL);
    } else {
        duk_push_pointer(ctx, (void *)myjs_handle.handle);
    }
    return 1;
}

static duk_ret_t native_myjs_close(duk_context *ctx)
{
    int8_t ret = -1;
    item_handle_t myjs_handle;

    if (!duk_is_pointer(ctx, 0)) {
        amp_warn(MOD_STR, "parameter must be handle");
        goto out;
    }

	amp_debug(MOD_STR, "_____>>>>>> native_myjs_close\n");
	
out:
    duk_push_int(ctx, ret);
    return 1;
}

int32_t myjs_value = 0;

static duk_ret_t native_myjs_read(duk_context *ctx)
{
    int32_t ret_val;
    item_handle_t myjs_handle;

    if (!duk_is_pointer(ctx, 0)) {
        amp_warn(MOD_STR, "parameter must be handle");
        goto out;
    }
	
	ret_val = myjs_value;
	myjs_value ++;
	
    amp_debug(MOD_STR, "_____>>>>>>  myjs value: %d\n", myjs_value);
	
out:
    duk_push_int(ctx, ret_val);
    return 1;
}

static duk_ret_t native_myjs_write(duk_context *ctx)
{
    int8_t result = -1;

    if (!duk_is_pointer(ctx, 0) || !duk_is_number(ctx, 1)) {
        amp_warn(MOD_STR, "parameter must be handle and number");
        goto out;
    }
    
	myjs_value = duk_get_int(ctx, 1);
	
    result = 0;
out:
    duk_push_int(ctx, result);
    return 1;
}

void module_myjs_register(void)
{
    duk_context *ctx = be_get_context();

    duk_push_object(ctx);

    AMP_ADD_FUNCTION("open",  native_myjs_open, 1);
    AMP_ADD_FUNCTION("read",  native_myjs_read, 1);
	AMP_ADD_FUNCTION("write",  native_myjs_write, 2);
    AMP_ADD_FUNCTION("close", native_myjs_close, 1);

    duk_put_prop_string(ctx, -2, "MYJS");
}
